<template>
  <div class="dataState">
    <div class='table'>
      <table id="data-stat-table">
        <!-- 表头标题行 -->
        <tr>
          <th colspan="16" class="title">
            <input type="text" style="text-align: right;
      height: 100%;
      color: #666;
    font-weight: bold;
    font-size: 22px;
      border: none;
      background-color: transparent;" v-model="city">今日数据分析表
    <input type="text" style="      border: none;
      height: 100%;background-color: transparent" disabled>  
    </th>
        </tr>
        <!-- 日期及各模块表头行 -->
        <tr style="
           font-weight: bold;
            font-size: 20px;
            text-align: center;">
          <td rowspan="2" style="text-align: center;">日期</td>
          <td colspan="6" style="text-align: center;">朋友圈</td>
          <td colspan="5" style="text-align: center;">粉丝</td>
          <td rowspan="2" style="text-align: center;" colspan="2">群数据</td>
          <td rowspan="2" style="text-align: center;" colspan="2">粉丝总数</td>
        </tr>
        <tr>
          <td>类型</td>
          <td>全天目标</td>
          <td>实际达成</td>
          <td>达成率</td>
          <td>转发量</td>
          <td>转发率</td>
          <td>类型</td>
          <td>全天目标</td>
          <td>实际完成</td>
          <td>达成率</td>
          <td>裂变比例</td>
        </tr>
        <!-- 内容行1 -->
        <tr>
          <td rowspan="5">{{ riqi }}</td>
          <td>被动发送</td>
          <td class="input"><input type="number" v-model="beidong.quantian" @change="re_beidong"></td>
          <td class="input"><input type="number" v-model="beidong.shiji" disabled></td>
          <td class="input">
            <span v-if="beidong.dachenglv">{{ beidong.dachenglv }}%</span>
          </td>
          <td class="input">{{ beidong.zhuanfaliang }}</td>
          <td class="input">
            <span v-if="beidong.zhuanfalv">{{ beidong.zhuanfalv }}%</span>
          </td>
          <td>自然裂变</td>
          <td class="input"><input type="number" v-model="ziranliebian.quantian" @change="re_ziranliebian"></td>
          <td class="input"><input type="number" v-model="ziranliebian.shiji" disabled></td>
          <td class="input">
            <span v-if="ziranliebian.dachenglv">{{ ziranliebian.dachenglv }}%</span>
          </td>
          <td class="input">{{ ziranliebian.bili }}</td>
          <td>新增群数量</td>
          <td class="input"><input type="number" v-model="qunshuju.xinzeng"></td>
          <td>不去重</td>
          <td class="input">{{fensizongshu.buquchong}}</td>
        </tr>
        <!-- 内容行2 -->
        <tr>
          <td>主动开发</td>
          <td class="input"><input type="number" v-model="zhudong.quantian" @change="re_zhudong"></td>
          <td class="input"><input type="number" v-model="zhudong.shiji" disabled></td>
          <td class="input">
            <span v-if="zhudong.dachenglv">{{ zhudong.dachenglv }}%</span>
          </td>
          <td class="input">{{ zhudong.zhuanfaliang }}</td>
          <td class="input">
            <span v-if="zhudong.zhuanfalv">{{ zhudong.zhuanfalv }}%</span>
          </td>
          <td>主动添加</td>
          <td class="input"><input type="number" v-model="zhudongtianjia.quantian" @change="re_zhudongtianjia"></td>
          <td class="input"><input type="number" v-model="zhudongtianjia.shiji" disabled></td>
          <td class="input">
            <span v-if="zhudongtianjia.dachenglv">{{ zhudongtianjia.dachenglv }}%</span>
          </td>
          <td class="input">{{ zhudongtianjia.bili }}</td>
          <td>群总数</td>
          <td class="input"><input type="number" v-model="qunshuju.qunzongshu"></td>
          <td>去重</td>
          <td class="input">{{fensizongshu.quchong}}</td>
        </tr>
        <!-- 内容行3 -->
        <tr>
          <td>摘抄同行</td>
          <td class="input"><input type="number" v-model="zhaichao.quantian" @change="re_zhaichao"></td>
          <td class="input"><input type="number" v-model="zhaichao.shiji" @change="re_zhaichao"></td>
          <td class="input">
            <span v-if="zhaichao.dachenglv">{{ zhaichao.dachenglv }}%</span>
          </td>
          <td class="input"><input type="number" v-model="zhaichao.zhuanfaliang" @change="re_zhaichao"></td>
          <td class="input">
            <span v-if="zhaichao.zhuanfalv">{{ zhaichao.zhuanfalv }}%</span>
          </td>

          <td class="input">
            <el-select v-model="other.type" style="width:120px" clearable @change="re_other" placeholder="请选择">
              <el-option value="群内引流">群内引流</el-option>
              <el-option value="小红书引流">小红书引流</el-option>
              <el-option value="boss引流">boss引流</el-option>
              <el-option value="兼职推广">兼职推广</el-option>
            </el-select>
          </td>
          <td class="input"><input type="number" v-model="other.quantian" @change="re_other"></td>
          <td class="input"><input type="number" v-model="other.shiji" disabled></td>
          <td class="input">
            <span v-if="other.dachenglv">{{ other.dachenglv }}%</span>
          </td>
          <td class="input">{{ other.bili }}</td>
          <td>群转化</td>
          <td class="input"><input type="number" v-model="qunshuju.qunzhuanhua"></td>
          <td></td>
          <td></td>
        </tr>
        <!-- 内容行4 -->
        <tr>
          <td>其他</td>
          <td class="input"><input type="number" v-model="qita.quantian" @change="re_qita"></td>
          <td class="input"><input type="number" v-model="qita.shiji" @change="re_qita"></td>
          <td class="input">
            <span v-if="qita.dachenglv">{{ qita.dachenglv }}%</span>
          </td>
          <td class="input"><input type="number" v-model="qita.zhuanfaliang" @change="re_qita"></td>
          <td class="input">
            <span v-if="qita.zhuanfalv">{{ qita.zhuanfalv }}%</span>
          </td>

          <td class="input">
            <el-select v-model="other1.type" style="width:120px" clearable @change="re_other1" placeholder="请选择">
              <el-option value="群内引流">群内引流</el-option>
              <el-option value="小红书引流">小红书引流</el-option>
              <el-option value="boss引流">boss引流</el-option>
              <el-option value="兼职推广">兼职推广</el-option>
            </el-select>
          </td>
          <td class="input"><input type="number" v-model="other1.quantian" @change="re_other1"></td>
          <td class="input"><input type="number" v-model="other1.shiji" disabled></td>
          <td class="input">
            <span v-if="other1.dachenglv">{{ other1.dachenglv }}%</span>
          </td>
          <td class="input">{{ other1.bili }}</td>
          <td></td>
          <td></td>
          <td>重数数量</td>
          <td class="input">{{fensizongshu.chongfushuliang}}</td>
        </tr>
        <!-- 内容行5 -->
        <tr>
          <td>每日广告条数</td>
          <td class="input"><input type="number" v-model="guanggao.quantian" @change="re_guanggao"></td>
          <td class="input"><input type="number" v-model="guanggao.shiji" @change="re_guanggao"></td>
          <td class="input">
            <span v-if="guanggao.dachenglv">{{ guanggao.dachenglv }}%</span>
          </td>
          <td class="input"><input type="number" v-model="guanggao.zhuanfaliang" @change="re_guanggao"></td>
          <td class="input">
            <span v-if="guanggao.zhuanfalv">{{ guanggao.zhuanfalv }}%</span>
          </td>

          <td class="input">
            <el-select v-model="other2.type" style="width:120px" clearable @change="re_other2" placeholder="请选择">
              <el-option value="群内引流">群内引流</el-option>
              <el-option value="小红书引流">小红书引流</el-option>
              <el-option value="boss引流">boss引流</el-option>
              <el-option value="兼职推广">兼职推广</el-option>
            </el-select>
          </td>
          <td class="input"><input type="number" v-model="other2.quantian" @change="re_other2"></td>
          <td class="input"><input type="number" v-model="other2.shiji" disabled></td>
          <td class="input">
            <span v-if="other2.dachenglv">{{ other2.dachenglv }}%</span>
          </td>
          <td class="input">{{ other2.bili }}</td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        <!-- 总结行 -->
        <tr>
          <td colspan="16">总结：
            <input type="text" style="width:90%;border:none;" v-model.sync="zongjie">
          </td>
        </tr>
      </table>
      <div style="display:flex;margin-top:10px;flex-direction: row-reverse;">
        <div style="display:flex;margin-top:10px;flex-direction: row;">
          <div style="line-height: 40px;margin-right: 10px;
          ">自然裂变微信：</div>
          <el-select v-model="ziranliebian.liebianWxid" placeholder="请选择引流微信" style="margin-right: 10px;min-width: 300px;"
            @change="re_ziranliebian" multiple>
            <el-option v-for="item in wechats" :key="item.WeChatId" :label="item.WeChatNick" :value="item.WeChatId">
            </el-option>
          </el-select>


          <div style="line-height: 40px;margin-right: 10px;" v-if="other.type">{{ other.type }}微信 | 第一个</div>
          <el-select v-if="other.type" v-model="other.otherWxid" placeholder="请选择引流微信" style="margin-right: 10px;min-width: 300px;"
            @change="re_other()" multiple>
            <el-option v-for="item in wechats" :key="item.WeChatId" :label="item.WeChatNick" :value="item.WeChatId">
            </el-option>
          </el-select>


          <div style="line-height: 40px;margin-right: 10px;" v-if="other1.type">{{ other1.type }}微信 | 第二个</div>
          <el-select v-if="other1.type" v-model="other1.otherWxid" placeholder="请选择引流微信" style="margin-right: 10px;min-width: 300px;"
            @change="re_other1()" multiple>
            <el-option v-for="item in wechats" :key="item.WeChatId" :label="item.WeChatNick" :value="item.WeChatId">
            </el-option>
          </el-select>


          <div style="line-height: 40px;margin-right: 10px;" v-if="other2.type">{{ other2.type }}微信 | 第三个</div>
          <el-select v-if="other2.type" v-model="other2.otherWxid" placeholder="请选择引流微信" style="margin-right: 10px;min-width: 300px;"
            @change="re_other2()" multiple>
            <el-option v-for="item in wechats" :key="item.WeChatId" :label="item.WeChatNick" :value="item.WeChatId">
            </el-option>
          </el-select>


          <el-button @click="save" type="primary" :disabled="cansave">{{ !cansave ? '保存今日数据分析' : '今日数据已提交' }}</el-button>
          <el-button @click="exportExcel" type="success" style="margin-left:10px;">
            导出Excel
          </el-button>
        </div>


      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { forwardStat, addStatistics, circleStatistics, saveStatData, queryStatData } from '@/api/admin/custom'
import dayjs from 'dayjs'
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'
import { friendData, circleData } from '@/api/front/data'

export default {
  name: 'dataStat',
  data() {
    return {
      city: '',
      beidong: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        zhuanfaliang: '',
        zhuanfalv: '',
      },
      zhudong: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        zhuanfaliang: '',
        zhuanfalv: '',
      },
      zhaichao: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        zhuanfaliang: '',
        zhuanfalv: '',
      },
      qita: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        zhuanfaliang: '',
        zhuanfalv: '',
      },
      guanggao: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        zhuanfaliang: '',
        zhuanfalv: '',
      },
      ziranliebian: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        liebianWxid: [],
      },
      zhudongtianjia: {
        quantian: '',
        shiji: '',
        dachenglv: '',
      },
      other: {
        type: '',
        quantian: '',
        shiji: '',
        dachenglv: '',
        otherWxid: [],
      },
      other1: {
        type: '',
        quantian: '',
        shiji: '',
        dachenglv: '',
        otherWxid: [],
      },
      other2: {
        type: '',
        quantian: '',
        shiji: '',
        dachenglv: '',
        otherWxid: [],
      },
      qunshuju: {
        xinzeng: '',
        qunzongshu: '',
        qunzhuanhua: '',
      },
      fensizongshu: {
        buquchong: '',
        quchong: '',
        chongfushuliang: '',
      },
      heji: {
        quantian: '',
        shiji: '',
        dachenglv: '',
        zhuanfaliang: '',
        fans_quantian: '',
        fans_shiji: '',
      },
      zongjie: '',
      riqi:  dayjs.unix(new Date().getTime() / 1000).format('YYYY-MM-DD'),
      forwardStat: [],
      circleStat: [],
      timeValue: [new Date(new Date().setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 999))],
      cansave: false
    }
  },
  computed: {
    ...mapGetters({
      //currentWeChatId: 'tools/currentWeChatId'
      wechats: 'conversation/wechats', // 会话页面 当前用户绑定的微信
      currentUser: 'currentUser',
    }),
    wechatList() {
      return this.wechats
    }
  },
  watch: {
    ziranliebian(val) {
      this.re_ziranliebian();
    },
    other(val) {
      this.re_other();
    },
    other1(val) {
      this.re_other1();
    },
    other2(val) {
      this.re_other2();
    },
  },
  async mounted() {
    // 如果该页面有选择微信 回显二维码
    await this.getStatDataByToday();
    if(this.cansave){
      this.re_zhudongtianjia();
      this.getforwardStat();
      this.getCircleStatistics();
      this.getCircleData();
    }
  },
  methods: {
        // 获取今日信息
        getCircleData() {
      this.todayData = []
      circleData(this.currentUser.SupplierId).then((res) => {
        if (res.code === 0 && res.data) {
          console.log(res.data);
          this.fensizongshu.buquchong = res.data.friendSize;
          this.fensizongshu.quchong = res.data.friendDistSize;
          this.fensizongshu.chongfushuliang = res.data.friendDistSize - res.data.friendSize;
        }
      })
    },
    async exportExcel() {
      try {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('今日数据分析表');
        const headerFill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'C1E7C1' } };
        const centerAlign = { vertical: 'middle', horizontal: 'center' };
        const borderStyle = { style: 'thin', color: { argb: '000000' } };
        const today = dayjs().format('YYYY-MM-DD');

        // 1. 标题行
        worksheet.mergeCells('A1:P1');
        worksheet.getCell('A1').value = '今日数据分析表';
        worksheet.getCell('A1').alignment = centerAlign;
        worksheet.getCell('A1').font = { name: '微软雅黑', size: 18, bold: true };
        worksheet.getCell('A1').fill = headerFill;
        worksheet.getRow(1).height = 30;
        worksheet.getRow(1).eachCell(cell => cell.border = { top: borderStyle, left: borderStyle, bottom: borderStyle, right: borderStyle });

        // 2. 一级表头
        worksheet.getCell('A2').value = '日期';
        worksheet.mergeCells('B2:G2');
        worksheet.getCell('B2').value = '朋友圈';
        worksheet.mergeCells('H2:L2');
        worksheet.getCell('H2').value = '粉丝';

        worksheet.getCell('M2').value = '群数据';

        worksheet.getCell('O2').value = '粉丝总数';
        ['A2', 'B2', 'H2', 'L2', 'M2', 'O2'].forEach(cell => {
          worksheet.getCell(cell).fill = headerFill;
          worksheet.getCell(cell).alignment = centerAlign;
          worksheet.getCell(cell).font = { bold: true, size: 13 };
          worksheet.getCell(cell).border = { top: borderStyle, left: borderStyle, bottom: borderStyle, right: borderStyle };
        });
        worksheet.getRow(2).height = 22;

        // 3. 二级表头
        worksheet.getRow(3).values = [
          '', '类型', '全天目标', '实际达成', '达成率', '转发量', '转发率',
          '类型', '全天目标', '实际完成', '达成率', '裂变比例'
        ];
        worksheet.getRow(3).eachCell(cell => {
          // cell.fill = headerFill;
          cell.alignment = centerAlign;
          cell.font = { bold: true, size: 12 };
          cell.border = { top: borderStyle, left: borderStyle, bottom: borderStyle, right: borderStyle };
        });
        worksheet.mergeCells('M2:N3');
        worksheet.mergeCells('O2:P3');
        // 4. 数据行
        // 朋友圈数据
        const pyqRows = [
          ['被动发送', this.beidong.quantian, this.beidong.shiji, this.beidong.dachenglv ? this.beidong.dachenglv + '%' : '', this.beidong.zhuanfaliang, this.beidong.zhuanfalv ? this.beidong.zhuanfalv + '%' : ''],
          ['主动开发', this.zhudong.quantian, this.zhudong.shiji, this.zhudong.dachenglv ? this.zhudong.dachenglv + '%' : '', this.zhudong.zhuanfaliang, this.zhudong.zhuanfalv ? this.zhudong.zhuanfalv + '%' : ''],
          ['摘抄同行', this.zhaichao.quantian, this.zhaichao.shiji, this.zhaichao.dachenglv ? this.zhaichao.dachenglv + '%' : '', this.zhaichao.zhuanfaliang, this.zhaichao.zhuanfalv ? this.zhaichao.zhuanfalv + '%' : ''],
          ['其他', this.qita.quantian, this.qita.shiji, this.qita.dachenglv ? this.qita.dachenglv + '%' : '', this.qita.zhuanfaliang, this.qita.zhuanfalv ? this.qita.zhuanfalv + '%' : ''],
          ['每日广告条数', this.guanggao.quantian, this.guanggao.shiji, this.guanggao.dachenglv ? this.guanggao.dachenglv + '%' : '', this.guanggao.zhuanfaliang, this.guanggao.zhuanfalv ? this.guanggao.zhuanfalv + '%' : ''],
        ];
        // 粉丝数据
        const fsRows = [
          ['自然裂变', this.ziranliebian.quantian, this.ziranliebian.shiji, this.ziranliebian.dachenglv ? this.ziranliebian.dachenglv + '%' : '', this.ziranliebian.bili],
          ['主动添加', this.zhudongtianjia.quantian, this.zhudongtianjia.shiji, this.zhudongtianjia.dachenglv ? this.zhudongtianjia.dachenglv + '%' : '', this.zhudongtianjia.bili],
          [this.other.type || '', this.other.quantian, this.other.shiji, this.other.dachenglv ? this.other.dachenglv + '%' : '', this.other.bili],
          [this.other1.type || '', this.other1.quantian, this.other1.shiji, this.other1.dachenglv ? this.other1.dachenglv + '%' : '', this.other1.bili],
          [this.other2.type || '', this.other2.quantian, this.other2.shiji, this.other2.dachenglv ? this.other2.dachenglv + '%' : '', this.other2.bili],
        ];
        // 群数据
        const qunRows = [
          ['新增群数量', this.qunshuju.xinzeng],
          ['群总数', this.qunshuju.qunzongshu],
          ['群转化', this.qunshuju.qunzhuanhua],
          ['', ''],
          ['', ''],
        ];
        // 粉丝总数
        const fszsRows = [
          ['不去重', this.fensizongshu.buquchong],
          ['去重', this.fensizongshu.quchong],
          ['', ''],
          ['重复', this.fensizongshu.chongfushuliang],
          ['', ''],
        ];

        for (let i = 0; i < 5; i++) {
          const rowIdx = 4 + i;
          const row = [
            i === 0 ? this.riqi : '', // 只A4有日期
            ...pyqRows[i],
            ...fsRows[i],
            ...qunRows[i],
            ...fszsRows[i]
          ];
          worksheet.getRow(rowIdx).values = row;
          worksheet.getRow(rowIdx).height = 20;
          worksheet.getRow(rowIdx).eachCell(cell => {
            cell.alignment = centerAlign;
            cell.border = { top: borderStyle, left: borderStyle, bottom: borderStyle, right: borderStyle };
          });
        }

                // 填充数据行
        worksheet.mergeCells('A3:A8');
        worksheet.getCell('A3').value = this.riqi;
        worksheet.getCell('A3').alignment = centerAlign;

        
        // 5. 总结行
        worksheet.mergeCells('A9:P9');
        worksheet.getCell('A9').value = '总结：' + (this.zongjie || '');
        worksheet.getCell('A9').alignment = { vertical: 'middle', horizontal: 'left' };
        worksheet.getCell('A9').font = { size: 12 };
        worksheet.getRow(9).eachCell(cell => {
          cell.border = { top: borderStyle, left: borderStyle, bottom: borderStyle, right: borderStyle };
        });

        // 6. 列宽
        const columnWidths = [12, 14, 12, 12, 12, 12, 12, 14, 12, 12, 12, 12, 14, 14, 14, 14];
        worksheet.columns.forEach((col, idx) => { col.width = columnWidths[idx]; });

        // 7. 导出
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, `${today}_今日数据分析表.xlsx`);
      } catch (e) {
        this.$message.error('导出失败，请重试');
      }
    },
    async getStatDataByToday() {
      let data = {
        cid: this.currentUser.SupplierId,
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      await queryStatData(data).then( async res => {
        console.log(res.data);
        //判断是否为空 或者为 {} 空对象
        if (res.data == null || res.data == {} || JSON.stringify(res.data) == "{}") {

          //获取前7天的数据。装入默认值
          let data = {
            cid: this.currentUser.SupplierId,
          }
          const now = new Date();
          // 计算七天前的时间戳（单位：毫秒，一天的毫秒数为 24 * 60 * 60 * 1000）
          const sevenDaysAgoTimeStamp = now.getTime() - 7 * 24 * 60 * 60 * 1000;
          // 根据时间戳创建七天前的 Date 对象
          const sevenDaysAgo = new Date(sevenDaysAgoTimeStamp);

          data.start_time = this.getTime(sevenDaysAgo);
          data.end_time = this.getTime(this.timeValue[1])
          await queryStatData(data).then(res => {
            let info = res.data;
            //如果内容是空
            if (info == null || info == {} || JSON.stringify(info) == "{}") {
              return;
            }
            this.beidong.quantian = info.beidong.quantian
            this.re_beidong()
            this.zhudong.quantian = info.zhudong.quantian
            this.re_zhudong()
            this.zhaichao.quantian = info.zhaichao.quantian
            this.re_zhaichao()
            this.qita.quantian = info.qita.quantian
            this.re_qita()
            this.guanggao.quantian = info.qita.quantian
            this.re_guanggao()
            this.ziranliebian.quantian = info.ziranliebian.quantian
            this.ziranliebian.liebianWxid = info.ziranliebian.liebianWxid
            this.re_ziranliebian()
            this.zhudongtianjia.quantian = info.zhudongtianjia.quantian
            this.re_zhudongtianjia()
            this.other.quantian = info.other.quantian
            this.other.type = info.other.type
            this.other.otherWxid = info.other.otherWxid
            this.re_other();
            this.other1.quantian = info.other1.quantian
            this.other1.type = info.other1.type
            this.other1.otherWxid = info.other1.otherWxid
            this.re_other1();
            this.other2.quantian = info.other2.quantian
            this.other2.type = info.other2.type
            this.other2.otherWxid = info.other2.otherWxid
            this.re_other2();
            this.zongjie = info.zongjie;
          });
          return;
        }
        this.cansave = true;
        this.beidong = res.data.beidong
        this.zhudong = res.data.zhudong
        this.zhaichao = res.data.zhaichao
        this.qita = res.data.qita
        this.guanggao = res.data.guanggao
        this.ziranliebian = res.data.ziranliebian
        this.zhudongtianjia = res.data.zhudongtianjia
        this.other = res.data.other
        this.other1 = res.data.other1
        this.other2 = res.data.other2
        this.qunshuju = res.data.qunshuju
        this.fensizongshu = res.data.fensizongshu
        this.zongjie = res.data.zongjie
        this.riqi = res.data.riqi
        this.city = res.data.city
        if(!this.city){
          this.city = '"请输入城市名称"';
        }
      })
    },
    save() {
      let arr = [];
      const allData = {
        beidong: this.beidong,
        zhudong: this.zhudong,
        zhaichao: this.zhaichao,
        qita: this.qita,
        guanggao: this.guanggao,
        ziranliebian: this.ziranliebian,
        zhudongtianjia: this.zhudongtianjia,
        other: this.other,
        other1: this.other1,
        other2: this.other2,
        qunshuju: this.qunshuju,
        fensizongshu: this.fensizongshu,
        city: this.city
      };
      Object.keys(allData).forEach(groupKey => {
        const group = allData[groupKey];
        Object.keys(group).forEach(key => {
          let value = group[key];
          let obj = {
            cid: this.currentUser.SupplierId,
            type: '今日数据分析表',
            name: groupKey + '.' + key,
            value: null,
            value_type: null,
            value_num: null,
            value_decimal: null,
            value_text: null,
            value_date: null
          };
          // 判断类型并赋值
          if (typeof value === 'number' || (!isNaN(value) && value !== '' && value !== null)) {
            // 整数
            if (Number.isInteger(Number(value))) {
              obj.value_type = 1;
              obj.value_num = Number(value);
            } else {
              // 浮点数
              obj.value_type = 2;
              obj.value_decimal = Number(value);
            }
          } else if (typeof value === 'string') {
            obj.value_type = 0;
            obj.value = value;
          } else if (value instanceof Date) {
            obj.value_type = 4;
            obj.value_date = value;
          } else {
            // 对象或数组
            obj.value_type = 3;
            obj.value_text = JSON.stringify(value);
          }
          arr.push(obj);
        });
      });

      // 总结
      if (this.zongjie) {
        arr.push({
          cid: this.currentUser.SupplierId,
          type: '今日数据分析表',
          name: 'zongjie',
          value_type: 0,
          value: this.zongjie,
          value_num: null,
          value_decimal: null,
          value_text: null,
          value_date: null
        });
      }
      if (this.riqi) {
        arr.push({
          cid: this.currentUser.SupplierId,
          type: '今日数据分析表',
          name: 'riqi',
          value_type: 0,
          value: this.riqi,
          value_num: null,
          value_decimal: null,
          value_text: null,
          value_date: null
        });
      }
      // 调用保存接口
      saveStatData({
        saveData: arr
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('保存成功');
          this.getStatDataByToday();
        } else {
          this.$message.error('保存失败');
        }
      }).catch(() => {
        this.$message.error('保存失败');
      });
    },
    jisuan(data) {
      if (data.shiji && data.quantian) {
        data.dachenglv = ((data.shiji / data.quantian) * 100).toFixed(2)
      } else {
        data.dachenglv = '';
      }
      if (data.shiji && data.zhuanfaliang) {
        data.zhuanfalv = ((data.zhuanfaliang / data.shiji) * 100).toFixed(2)
      } else {
        data.zhuanfalv = '';
      }
    },
    re_beidong() {
      this.jisuan(this.beidong);
    },
    re_zhudong() {
      this.jisuan(this.zhudong);
    },
    re_zhaichao() {
      this.jisuan(this.zhaichao);
    },
    re_qita() {
      this.jisuan(this.qita);
    },
    re_guanggao() {
      this.jisuan(this.guanggao);
    },
    re_other() {
      if (!this.other.type || !this.other.otherWxid || this.other.otherWxid.length == 0) {
        this.other.shiji = 0;
        this.other.dachenglv = 0;
        this.other.bili = 0;
        this.other.quantian = 0;
        this.other.otherWxid = [];
        return;
      }
      let data = {
        cid: this.currentUser.SupplierId,
        add_type: 1,
        wxid: this.other.otherWxid
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      addStatistics(data).then(res => {
        if (!res.data || res.data.length == 0) {
          this.other.shiji = 0;
        } else {
          res.data.forEach(item => {
            if (item.add_type == 1) {
              this.other.shiji = item.num;
            }
          });
        }
        if (this.other.quantian) {
          //百分比
          this.other.dachenglv = ((this.other.shiji / this.other.quantian) * 100).toFixed(2)
        }
        if (this.other.shiji) {
          //获取
          let sum = 0;
          this.forwardStat.forEach(item => {
            if (this.other.otherWxid.includes(item.wxid)) {
              sum += item.type_peng;
              sum += item.type_qun;
            }
          });
          //获取比例
          this.other.bili = ((this.other.shiji / sum)).toFixed(3);
        }
      });
    },
    re_other1() {
      if (!this.other1.type || !this.other1.otherWxid || this.other1.otherWxid.length == 0) {
        this.other1.shiji = null;
        this.other1.quantian = null;
        this.other1.dachenglv = null;
        this.other1.bili = null;
        this.other1.otherWxid = [];
        return;
      }
      let data = {
        cid: this.currentUser.SupplierId,
        add_type: 1,
        wxid: this.other1.otherWxid
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      addStatistics(data).then(res => {
        if (!res.data || res.data.length == 0) {
          this.other1.shiji = 0;
        } else {
          res.data.forEach(item => {
            if (item.add_type == 1) {
              this.other1.shiji = item.num;
            }
          });
        }
        if (this.other1.quantian) {
          //百分比
          this.other1.dachenglv = ((this.other1.shiji / this.other1.quantian) * 100).toFixed(2)
        }
        if (this.other1.shiji) {
          //获取
          let sum = 0;
          this.forwardStat.forEach(item => {
            if (this.other1.otherWxid.includes(item.wxid)) {
              sum += item.type_peng;
              sum += item.type_qun;
            }
          });
          //获取比例
          this.other1.bili = ((this.other1.shiji / sum)).toFixed(3);
        }
      });
    },
    re_other2() {
      if (!this.other2.type || !this.other2.otherWxid || this.other2.otherWxid.length == 0) {
        this.other2.shiji = null;
        this.other2.quantian = null;
        this.other2.dachenglv = null;
        this.other2.bili = null;
        this.other2.otherWxid = [];
        return;
      }
      let data = {
        cid: this.currentUser.SupplierId,
        add_type: 1,
        wxid: this.other2.otherWxid
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      addStatistics(data).then(res => {
        if (!res.data || res.data.length == 0) {
          this.other2.shiji = 0;
        } else {
          res.data.forEach(item => {
            if (item.add_type == 1) {
              this.other2.shiji = item.num;
            }
          });
        }
        if (this.other2.quantian) {
          //百分比
          this.other2.dachenglv = ((this.other2.shiji / this.other2.quantian) * 100).toFixed(2);
        }
        if (this.other2.shiji) {
          //获取
          let sum = 0;
          this.forwardStat.forEach(item => {
            if (this.other2.otherWxid.includes(item.wxid)) {
              sum += item.type_peng;
              sum += item.type_qun;
            }
          });
          //获取比例
          this.other2.bili = ((this.other2.shiji / sum)).toFixed(3);
        }
      });
    },
    re_ziranliebian() {
      console.log(this.ziranliebian);
      if (!this.ziranliebian.liebianWxid || this.ziranliebian.liebianWxid.length == 0) {
        this.ziranliebian.shiji = null;
        this.ziranliebian.bili = null;
        this.ziranliebian.dachenglv = null;
        return;
      }
      let data = {
        cid: this.currentUser.SupplierId,
        add_type: 1,
        wxid: this.ziranliebian.liebianWxid
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      addStatistics(data).then(res => {
        if (!res.data || res.data.length == 0) {
          this.ziranliebian.shiji = 0;
        } else {
          res.data.forEach(item => {
            if (item.add_type == 1) {
              this.ziranliebian.shiji = item.num;
            }
          });
        }
        if (this.ziranliebian.shiji) {
          //获取
          let sum = 0;
          this.forwardStat.forEach(item => {
            if (this.ziranliebian.liebianWxid.includes(item.wxid)) {
              sum += item.type_peng;
              sum += item.type_qun;
            }
          });
          //获取比例
          this.ziranliebian.bili = ((this.ziranliebian.shiji / sum)).toFixed(3);
        }
        if (this.ziranliebian.quantian) {
          //百分比
          this.ziranliebian.dachenglv = ((this.ziranliebian.shiji / this.ziranliebian.quantian) * 100).toFixed(2)
        }
      });
    },
    re_zhudongtianjia() {
      //计算所有账号的主动添加总数
      let data = {
        cid: this.currentUser.SupplierId,
        add_type: 0
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      addStatistics(data).then(res => {
        if (!res.data  || res.data.length == 0) {
          this.zhudongtianjia.shiji = 0;
        } else {
          res.data.forEach(item => {
            if (item.add_type == 0) {
              this.zhudongtianjia.shiji = item.num;
            }
          });
        }
        if (this.zhudongtianjia.quantian) {
          //百分比
          this.zhudongtianjia.dachenglv = ((this.zhudongtianjia.shiji / this.zhudongtianjia.quantian) * 100).toFixed(2)
        }
      });
    },
    getTime(date) {
      //返回 yyyy-mm-dd hh:MM:ss
      return dayjs.unix(date.getTime() / 1000).format('YYYY-MM-DD HH:mm:ss')
    },
    getforwardStat() {
      let data = {
        cid: this.currentUser.SupplierId,
      }
      data.start_time = this.getTime(this.timeValue[0])
      data.end_time = this.getTime(this.timeValue[1])
      forwardStat(data).then(res => {
        this.forwardStat = res.data;
        //this.forwardStat所有的 type_peng+type_qun的总和 
        let sum = 0;
        this.forwardStat.forEach(item => {
          sum += item.type_peng;
          sum += item.type_qun;
        });
        this.beidong.zhuanfaliang = sum;
        this.re_beidong();
        this.zhudong.zhuanfaliang = sum;
        this.re_zhudong();
      })
    },
    getCircleStatistics() {
      let data = {
        cid: this.currentUser.SupplierId,
      }
      data.startTime = this.getTime(this.timeValue[0])
      data.endTime = this.getTime(this.timeValue[1])
      circleStatistics(data).then(res => {
        console.log(res.data);
        this.circleStat = res.data;
        if (this.circleStat.length > 0) {
          //设置被动实际达成 item.send_type==0 满足的 item.total的总和
          this.beidong.shiji = this.circleStat.filter(item => item.send_type == 1).reduce((total, item) => {
            return total + item.total
          }, 0);
        }else{
          this.beidong.shiji = 0;
        }
        this.re_beidong();
        //设置主动实际达成
        if (this.circleStat.length > 0) {
          this.zhudong.shiji = this.circleStat.filter(item => item.send_type == 0).reduce((total, item) => {
            return total + item.total
          }, 0);
        }else{
          this.zhudong.shiji = 0;
        }
        this.re_zhudong();
      })
    },
    changeOtherWxid() {
      console.log(this.otherWxid)
    },
    changeLiebianWxid() {
      console.log(this.ziranliebian.liebianWxid)
    }

  }
}
</script>

<style lang="scss" scoped>
.dataState {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: scroll;
}

.table {
  width: 95%;

  table {
    width: 100%;
    border-collapse: collapse;
    text-align: center;
  }

  th,
  td {
    border: 1px solid #000;
    padding: 8px;
    text-align: center !important;
  }

  .input {
    width: 100px;
    padding: 0px;

    input {
      text-align: center;
      width: 100%;
      height: 100%;
      border: none;
      background-color: transparent;
    }

    select {
      width: 100%;
      height: 100%;
      border: none;
    }
  }

  .title {
    background-color: lightgreen;
    font-weight: bold;
    text-align: center;
    font-size: 22px;
  }

  .total {
    background-color: orange;
  }
}
</style>
